package com.framework.service.common.impl;

import com.framework.common.enums.annex.GroupStatusEnum;
import com.framework.common.model.response.R;
import com.framework.common.util.minio.MinioUtil;
import com.framework.common.util.other.NumeralUtil;
import com.framework.common.util.other.SymbolUtil;
import com.framework.common.util.redis.RedisKeyUtil;
import com.framework.common.util.redis.RedisPrefixUtil;
import com.framework.mapper.common.GroupMapper;
import com.framework.mapper.common.TypeMapper;
import com.framework.model.common.vo.GroupVo;
import com.framework.model.system.vo.SystemUserVo;
import com.framework.service.base.BaseService;
import com.framework.service.common.GroupService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 龘鵺
 * @version 1.0
 * @className com.framework.service.common.impl.GroupServiceImpl
 * @description 附件分组业务接口实现类
 * @datetime 2024-08-19 16:04:27
 */
@Service("groupServiceImpl")
public class GroupServiceImpl extends BaseService implements GroupService {
    private Logger log = LoggerFactory.getLogger(GroupServiceImpl.class);
    /** 桶名称 */
    @Value("${custom.minio.bucketName}")
    private String bucketName;
    @Autowired
    private GroupMapper groupMapper;
    @Autowired
    private TypeMapper typeMapper;
    @Autowired
    private MinioUtil minioUtil;

    /**
     * @param id 1 编号
     * @return com.framework.model.common.vo.GroupVo
     * @title 根据编号查询附件分组
     * @description 根据编号查询附件分组
     * @author 龘鵺
     * @datetime 2024-08-19 16:04:27
     * @version 1.0
     */
    @Override
    public GroupVo getByIdParam(Long id) {
        GroupVo row = new GroupVo();
        row.setId(id);
        SystemUserVo systemUserVo = getUser();
        row.setGtaeOperaterStatus(NumeralUtil.POSITIVE_ONE);
        GroupVo p = groupMapper.selectByParam(row);
        if (p == null) {
            return new GroupVo();
        }
        return p;
    }

    /**
     * @param row 1 附件分组类
     * @return com.framework.common.model.response.R
     * @title 新增附件分组
     * @description 新增附件分组
     * @author 龘鵺
     * @datetime 2024-08-19 16:04:27
     * @version 1.0
     */
    @Override
    @Transactional
    public R<?> save(GroupVo row) throws Exception {
        SystemUserVo systemUserVo = getUser();
//        TypeVo type = new TypeVo();
//        type.setParentTypeCode("dataSource");
//        type.setTypeValue(row.getSources());
//        type = typeMapper.selectByParam(type);
//        if (type == null) {
//            return R.fail("数据来源错误!");
//        }
//        row.setCode(row.getCode() + SymbolUtil.NO_INPUT_METHOD_MINUS_SIGN + type.getTypeCode().toLowerCase());

        int num = groupMapper.isExist(row);
        if (num > NumeralUtil.POSITIVE_ZERO) {
            return R.fail();
        }
        row.setId(null);
        Long userId = systemUserVo.getId();
        Date date = new Date();
        row.setOperaterTime(date);
        row.setCreateId(userId);
        row.setOperaterId(userId);
        row.setCreateTime(date);
        row.setOperaterStatus(NumeralUtil.POSITIVE_ONE);
        groupMapper.insertSelective(row);
        return R.ok();
    }

    /**
     * @param row 1 附件分组类
     * @return com.framework.common.model.response.R
     * @title 编辑附件分组
     * @description 编辑附件分组
     * @author 龘鵺
     * @datetime 2024-08-19 16:04:27
     * @version 1.0
     */
    @Override
    @Transactional
    public R<?> edit(GroupVo row) throws Exception {
        SystemUserVo systemUserVo = getUser();
        GroupVo queryParam = new GroupVo();
        queryParam.setId(row.getId());
        queryParam.setGtaeOperaterStatus(NumeralUtil.POSITIVE_ONE);
        queryParam = groupMapper.selectByParam(queryParam);
        if (queryParam == null) {
            return R.fail("编辑信息不存在!");
        }
        Long userId = systemUserVo.getId();
        Date date = new Date();
        row.setOperaterStatus(NumeralUtil.POSITIVE_TWO);
        row.setOperaterId(userId);
        row.setOperaterTime(date);
//        row.setCode(null);
        if (!row.getStatus().equalsIgnoreCase(queryParam.getStatus())) {
            GroupVo groupVo = new GroupVo();
            groupVo.setGtaeOperaterStatus(NumeralUtil.POSITIVE_ZERO);
            List<GroupVo> groupVoList = groupMapper.findByListTwo(groupVo);
            if (groupVoList.size() == NumeralUtil.POSITIVE_ZERO) {
                return R.fail("数据不存在!");
            }
            /** 只读 */
            List<String> readonly = new ArrayList<>(groupVoList.size());
            /** 只写 */
            List<String> writeonly = new ArrayList<>(groupVoList.size());
            /** 读写 */
            List<String> readwrite = new ArrayList<>(groupVoList.size());
            StringBuilder s3 = new StringBuilder();
            for (GroupVo item : groupVoList) {
                if (item.getId().longValue() == row.getId().longValue()) {
                    item.setStatus(row.getStatus());
                }
                s3.append("\"").append(MinioUtil.ARN_AWS_S3).append(bucketName).append(SymbolUtil.NO_INPUT_METHOD_FORWARD_SLASH)
                        .append(item.getCode()).append(SymbolUtil.NO_INPUT_METHOD_FORWARD_SLASH).append(SymbolUtil.NO_INPUT_METHOD_ASTERISK)
                        .append(SymbolUtil.NO_INPUT_METHOD_ASTERISK).append("\"");
                //读写
                if (GroupStatusEnum.code5.getStatus().equalsIgnoreCase(item.getStatus())) {
                    readwrite.add(s3.toString());
                    s3.setLength(0);
                    continue;
                }
                //只写（包含删除）
                if (GroupStatusEnum.code4.getStatus().equalsIgnoreCase(item.getStatus())) {
                    writeonly.add(s3.toString());
                    s3.setLength(0);
                    continue;
                }
                //只读
                if (GroupStatusEnum.code3.getStatus().equalsIgnoreCase(item.getStatus())) {
                    readonly.add(s3.toString());
                    s3.setLength(0);
                    continue;
                }
                s3.setLength(0);
            }
//            readonly = new ArrayList<>();
//            writeonly = new ArrayList<>();
//            readwrite = new ArrayList<>();
            StringBuilder content = new StringBuilder();
            if (readonly.size() > NumeralUtil.POSITIVE_ZERO) {
                content.append(SymbolUtil.NO_INPUT_METHOD_COMMA);
                content.append(MinioUtil.READ_CONTENT.replace(MinioUtil.READONLY_PARAM, readonly.toString()));
            }
            if (writeonly.size() > NumeralUtil.POSITIVE_ZERO) {
                content.append(SymbolUtil.NO_INPUT_METHOD_COMMA);
                content.append(MinioUtil.WRITE_CONTENT.replace(MinioUtil.WRITEONLY_PARAM, writeonly.toString()));
            }
            if (readwrite.size() > NumeralUtil.POSITIVE_ZERO) {
                content.append(SymbolUtil.NO_INPUT_METHOD_COMMA);
                content.append(MinioUtil.READ_WRITE_CONTENT.replace(MinioUtil.READ_WRITE_PARAM, readwrite.toString()));
            }
            String con = MinioUtil.TOTAL_CONTENT.replace(MinioUtil.READWRITE_CONTENT, content);
            minioUtil.setBucketPolicy(bucketName, con);
        }
        groupMapper.updateByPrimaryKeySelective(row);
        return R.ok();
    }

    /**
     * @param id 1 编号
     * @return com.framework.common.model.response.R
     * @title 删除附件分组
     * @description 删除附件分组
     * @author 龘鵺
     * @datetime 2024-08-19 16:04:27
     * @version 1.0
     */
    @Override
    @Transactional
    public R<?> delete(Long id) {
        GroupVo row = new GroupVo();
        Date date = new Date();
        SystemUserVo systemUserVo = getUser();
        Long userId = systemUserVo.getId();
        row.setId(id);
        row.setOperaterTime(date);
        row.setOperaterId(userId);
        row.setOperaterStatus(NumeralUtil.NEGATIVE_ONE);
        groupMapper.delete(row);
        return R.ok();
    }

    /**
     * @param idList 1 编号集合
     * @return com.framework.common.model.response.R
     * @title 批量删除附件分组
     * @description 批量删除附件分组
     * @author 龘鵺
     * @datetime 2024-08-19 16:04:27
     * @version 1.0
     */
    @Override
    @Transactional
    public R<?> batchDeleteList(List<Long> idList) {
        GroupVo row = new GroupVo();
        SystemUserVo systemUserVo = getUser();
        Long userId = systemUserVo.getId();
        Date date = new Date();
        row.setIdList(idList);
        row.setOperaterTime(date);
        row.setOperaterId(userId);
        row.setOperaterStatus(NumeralUtil.NEGATIVE_ONE);
        //groupMapper.deleteList(row);
        return R.ok();
    }

    /**
     * @param row 1 附件分组类
     * @return java.util.List<com.framework.model.common.vo.GroupVo>
     * @title 查询附件分组集合
     * @description 查询附件分组集合
     * @author 龘鵺
     * @datetime 2024-08-19 16:04:27
     * @version 1.0
     */
    @Override
    public List<GroupVo> findByList(GroupVo row) {
        SystemUserVo systemUserVo = getUser();
        row.setGtaeOperaterStatus(NumeralUtil.POSITIVE_ONE);
        List<GroupVo> list = groupMapper.findByList(row);
        return list;
    }

    /**
     * @param row 1 附件分组类
     * @return com.framework.common.model.response.R
     * @title 分页查询附件分组列表
     * @description 分页查询附件分组列表
     * @author 龘鵺
     * @datetime 2024-08-19 16:04:27
     * @version 1.0
     */
    @Override
    public R<?> findParamPageList(GroupVo row) {
        SystemUserVo systemUserVo = getUser();
        row.setGtaeOperaterStatus(NumeralUtil.POSITIVE_ONE);
        int count = groupMapper.findPageListCount(row);
        if (count == NumeralUtil.POSITIVE_ZERO) {
            return R.ok();
        }
        List<GroupVo> list = groupMapper.findPageList(row);
        return R.ok(list, count);
    }


    /**
     * @param id 1 编号
     * @return com.framework.common.model.response.R
     * @title 启用禁用方法
     * @description 启用禁用方法
     * @author 龘鵺
     * @datetime 2024-08-19 16:04:27
     */
    @Override
    public R<?> enable(Long id) {
        String timeKey = RedisKeyUtil.getObjKey(RedisPrefixUtil.PREFIX_STR_GROUP_ENABLE_KEY, RedisPrefixUtil.PREFIX_STR_GROUP_ENABLE_KEY, id.toString());
        long expireNum = redisUtil.getExpire(timeKey);
        if (expireNum > NumeralUtil.POSITIVE_ZERO) {
            return R.fail("操作频繁,请" + expireNum + "秒后重试!");
        }
        GroupVo queryParam = new GroupVo();
        SystemUserVo systemUserVo = getUser();
        queryParam.setId(id);
        queryParam.setGtaeOperaterStatus(NumeralUtil.POSITIVE_ONE);
        queryParam = groupMapper.selectByParam(queryParam);
        if (queryParam == null) {
            return R.fail("信息不存在!");
        }
        redisUtil.setString(timeKey, NumeralUtil.STRING_POSITIVE_ZERO, NumeralUtil.POSITIVE_TEN);
        Long userId = systemUserVo.getId();
        Date date = new Date();
        GroupVo row = new GroupVo();
        row.setOperaterId(userId);
        row.setOperaterTime(date);
        row.setOperaterStatus(NumeralUtil.POSITIVE_TWO);
        row.setId(queryParam.getId());
        if (queryParam.getEnableStatus().intValue() == NumeralUtil.POSITIVE_ONE) {
            row.setEnableStatus(NumeralUtil.POSITIVE_TWO);
        } else {
            row.setEnableStatus(NumeralUtil.POSITIVE_ONE);
        }
        groupMapper.updateByPrimaryKeySelective(row);
        return R.ok();
    }

}